<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="计划名称" prop="planName">
        <el-input v-model="queryParams.planName" placeholder="请输入计划名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="巡检类型" prop="planType">
        <el-select v-model="queryParams.planType" placeholder="请选择巡检类型" clearable size="small">
             <el-option v-for="dict in this.getDictDatas(DICT_TYPE.M_PLAN_TYPE)" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
        </el-select>
      </el-form-item>
      <el-form-item label="周期编码" prop="cycleCode">
        <el-input v-model="queryParams.cycleCode" placeholder="请输入周期编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="周期名称" prop="cycleName">
        <el-input v-model="queryParams.cycleName" placeholder="请输入周期名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="所属部门" prop="deptId">
        <treeselect v-model="queryParams.deptId" :options="deptList" :normalizer="normalizer" placeholder="选择所属部门" style="width: 200px"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['devices:maintenance-plan:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['devices:maintenance-plan:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['devices:maintenance-plan:delete']"
        >
          批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column label="计划名称" align="center" prop="planName"/>
      <el-table-column label="巡检类型" align="center" prop="planType">
        <template v-slot="scope">
          {{ getDictDataLabel(DICT_TYPE.M_PLAN_TYPE, scope.row.planType) }}
        </template>
      </el-table-column>
      <el-table-column label="周期编码" align="center" prop="cycleCode"/>
      <el-table-column label="周期名称" align="center" prop="cycleName"/>
      <el-table-column label="部门名称" align="center" prop="deptName"/>
      <!-- 已删除设备集合列 -->
      <el-table-column label="执行人名称" align="center" prop="executorUserName"/>
<!--      <el-table-column label="所需时间(min)" align="center" prop="planUseTime"/>-->
      <el-table-column label="描述" align="center" prop="description" show-overflow-tooltip/>
      <el-table-column label="状态" align="center" prop="status">
         <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
<!--          <span>{{ parseTime(scope.row.createTime) }}</span>-->
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                     v-hasPermi="['devices:maintenance-plan:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['devices:maintenance-plan:delete']">删除
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="showDevices(scope.row)"
                     v-hasPermi="['devices:maintenance-plan:query']">查看设备
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-document" @click="showPlanItems(scope.row)"
                     v-hasPermi="['devices:maintenance-plan:query']">计划内容
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <MaintenancePlanForm ref="formRef" @success="getList"/>

    <!-- 设备列表对话框 -->
    <el-dialog title="设备列表" :visible.sync="deviceDialogVisible" width="700px" v-dialogDrag append-to-body>
      <el-table
        :data="currentDevicesList"
        :stripe="true"
        :show-overflow-tooltip="true"
        size="small"
      >
        <el-table-column type="index" label="序号" width="50"/>
        <el-table-column label="设备编号" align="center" prop="deviceCode"/>
        <el-table-column label="设备名称" align="center" prop="deviceName"/>
      </el-table>
    </el-dialog>

    <!-- 计划内容对话框 -->
      <el-dialog
        :title="`计划内容 - ${currentPlanName}`"
        :visible.sync="planItemDialogVisible"
        width="1500px"
        v-dialogDrag
        append-to-body
        @open="handlePlanItemDialogOpen"
        @close="handlePlanItemDialogClose"
      >
        <!-- 引入计划内容页面组件 -->
        <plan-item-view
          ref="planItemComponentRef"
          @component-loaded="savePlanItemComponentRef"
        />
      </el-dialog>
  </div>
</template>

<script>
import * as MaintenancePlanApi from '@/api/devices/maintenanceplan/index.js';
import * as MaintenancePlanItemApi from '@/api/devices/maintenanceplanitem';
import MaintenancePlanForm from './MaintenancePlanForm.vue';
// 动态导入计划内容页面组件
const PlanItemView = () => import('@/views/devices/maintenanceplanitem/index.vue');
import {listDept} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "MaintenancePlan",
  components: {
    MaintenancePlanForm,
    Treeselect,
    PlanItemView
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备/工装巡检计划列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 部门列表
      deptList: [],
      // 设备列表对话框可见性
      deviceDialogVisible: false,
      // 当前行设备列表
      currentDevicesList: [],
      // 计划内容对话框可见性
      planItemDialogVisible: false,
      // 当前计划ID
      currentPlanId: null,
      // 当前计划名称
      currentPlanName: null,
      // 计划内容加载状态
      planItemLoading: false,
      // 计划内容总条数
      planItemTotal: 0,
      // 计划内容列表
      planItemList: [],
      // 计划内容选中ID
      planItemCheckedIds: [],
      // 计划内容查询参数
      planItemQueryParams: {
        pageNo: 1,
        pageSize: 10,
        maintenancePlanId: null,
        planContent: null,
        sort: null
      },
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        maintenanceCycleId: null,
        cycleType: 1, // 默认值设为1
        planName: null,
        planType: null,
        cycleCode: null,
        cycleName: null,
        deptId: null,
        deptName: null,
        devicesList: null,
        executorUserId: null,
        executorUserName: null,
        planUseTime: [],
        description: null,
        status: null,
        createTime: [],
      },
    };
  },
  created() {
    this.getList();
    this.getOptions();
  },
  methods: {
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      // 关键：如果不是第三级节点，则禁用
      return {
        id: node.id,
        label: node.name,
        children: node.children, // 必须包含 children
      };
    },
    getOptions() {
      listDept().then(response => {
        this.deptList = this.handleTree(response.data, "id")[0].children;
      });
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await MaintenancePlanApi.getMaintenancePlanPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 重置后保持cycleType=1
      this.queryParams.cycleType = 1;
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除该条数据?')
      try {
        await MaintenancePlanApi.deleteMaintenancePlan(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除设备/工装巡检计划 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await MaintenancePlanApi.deleteMaintenancePlanList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有设备/工装巡检计划数据项?');
      try {
        this.exportLoading = true;
        const data = await MaintenancePlanApi.exportMaintenancePlanExcel(this.queryParams);
        this.$download.excel(data, '设备/工装巡检计划.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
    /** 显示设备列表 */
    showDevices(row) {
      this.currentDevicesList = row.devicesList || [];
      this.deviceDialogVisible = true;
    },

    /** 显示计划内容 */
    async showPlanItems(row) {
      this.currentPlanId = row.id;
      this.currentPlanName = row.planName;
      this.planItemQueryParams.maintenancePlanId = row.id;
      
      // 延迟打开对话框，确保组件引用和数据准备就绪
      setTimeout(() => {
        this.planItemDialogVisible = true;
        // 立即设置维护计划ID，不等待对话框完全打开
        if (this.planItemComponentRef && this.currentPlanId) {
          this.planItemComponentRef.setMaintenancePlanId(this.currentPlanId);
        }
      }, 0);
    },
    
    /** 处理计划内容对话框打开 */
    handlePlanItemDialogOpen() {
      // 对话框打开时再次确保维护计划ID已设置（双重保障）
      if (this.planItemComponentRef && this.currentPlanId) {
        this.planItemComponentRef.setMaintenancePlanId(this.currentPlanId);
      }
    },

    /** 处理计划内容对话框关闭 */
    handlePlanItemDialogClose() {
      // 对话框关闭时清理引用
      this.currentPlanId = null;
      this.currentPlanName = null;
    },

    /** 保存计划内容组件引用 */
    savePlanItemComponentRef(component) {
      this.planItemComponentRef = component;
      // 如果组件加载后维护计划ID已存在，立即设置
      if (this.currentPlanId) {
        // 使用nextTick确保组件完全初始化
        this.$nextTick(() => {
          component.setMaintenancePlanId(this.currentPlanId);
        });
      }
    },

    /** 获取计划内容列表（保留以备后续使用） */
    async getPlanItemList() {
      try {
        this.planItemLoading = true;
        const res = await MaintenancePlanItemApi.getMaintenancePlanItemPage(this.planItemQueryParams);
        this.planItemList = res.data.list;
        this.planItemTotal = res.data.total;
      } finally {
        this.planItemLoading = false;
      }
    },

    /** 计划内容搜索 */
    handlePlanItemQuery() {
      this.planItemQueryParams.pageNo = 1;
      this.getPlanItemList();
    },

    /** 计划内容重置搜索 */
    resetPlanItemQuery() {
      this.planItemQueryParams.planContent = null;
      this.planItemQueryParams.sort = null;
      this.handlePlanItemQuery();
    },

    /** 新增计划内容 */
    openPlanItemForm(id = undefined) {
      // 创建临时表单对话框
      const dialog = this.$dialog.form({
        title: id ? '编辑计划内容' : '新增计划内容',
        width: '800px',
        url: () => import('@/views/devices/maintenanceplanitem/MaintenancePlanItemForm.vue'),
        props: {
          defaultMaintenancePlanId: this.currentPlanId
        },
        params: {
          id: id
        },
        done: () => {
          this.getPlanItemList();
        },
        props: {
          // 传递维护计划ID，用于新增时自动设置
          defaultMaintenancePlanId: id ? undefined : this.currentPlanId
        }
      });

      // 如果是编辑，打开后加载数据
      if (id) {
        dialog.then(form => form.open(id));
      } else {
        // 新增时，打开后设置默认的维护计划ID
        dialog.then(form => {
          form.open().then(() => {
            if (form.formData && this.currentPlanId) {
              form.formData.maintenancePlanId = this.currentPlanId;
              // 由于是动态导入，这里我们需要触发一次搜索来加载维护计划列表
              form.getMaintenancePlanList().then(() => {
                // 强制更新表单验证状态
                if (form.$refs.formRef) {
                  form.$refs.formRef.validateField('maintenancePlanId');
                }
              });
            }
          });
        });
      }
    },

    /** 删除计划内容 */
    async handlePlanItemDelete(row) {
      const id = row.id;
      await this.$modal.confirm(`是否确认删除计划内容?`);
      try {
        await MaintenancePlanItemApi.deleteMaintenancePlanItem(id);
        await this.getPlanItemList();
        this.$modal.msgSuccess("删除成功");
      } catch {}
    },

    /** 批量删除计划内容 */
    async handlePlanItemDeleteBatch() {
      if (this.planItemCheckedIds.length === 0) {
        this.$modal.msgWarning("请选择要删除的计划内容");
        return;
      }
      await this.$modal.confirm(`是否确认删除选中的${this.planItemCheckedIds.length}条计划内容?`);
      try {
        await MaintenancePlanItemApi.deleteMaintenancePlanItemList(this.planItemCheckedIds);
        this.planItemCheckedIds = [];
        await this.getPlanItemList();
        this.$modal.msgSuccess("删除成功");
      } catch {}
    },

    /** 计划内容选中变化 */
    handlePlanItemRowCheckboxChange(records) {
      this.planItemCheckedIds = records.map((item) => item.id);
    }
  }
};
</script>
